package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.vo.PaySheetFromBalanceListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.paybalance.pojo.dto.PaySheetFromBalanceDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.service.PayBalanceService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 徐俊杰
 * @date 2020/3/3 16:55
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/payBalance")
public class PayBalanceController {
    @Resource
    private PayBalanceService payBalanceService;
    @RequestMapping(value = "/paySheet", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String paymentUnGet(@RequestBody @Valid PaySheetFromBalanceDTO paySheetFromBalanceDTO, BindingResult br) {
        XbbResponse<PaySheetFromBalanceListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.PAY_SHEET.getCode(), null, paySheetFromBalanceDTO.getDistributorMark());
                PaySheetFromBalanceListVO paasFormDataEsListVO = payBalanceService.paySheetFromBalanceList(paySheetFromBalanceDTO);
                response = new XbbResponse<>(paasFormDataEsListVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
